import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { Card, Button, Accordion, List, Modal, Stepper, Tabs, Toast } from "antd-mobile";
import { Row, Col } from "antd";
import { ROUTE_PATH, PAGE_TYPE, encodeUrlParam } from "src/projects/app/util-tool";
import { request } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { getUuid } from "src/business/util_tool";

import './index.less';

// TODO: 平台id以及慈善id均写死
const divideTitleMap = {
    '平台': '7e7e2fec-d91d-11e9-8e1d-983b8f0bcd67',
    '慈善': '567c9bd8-0208-11ea-9b57-7c2a3115762d',
    '服务商': ''
};
/**
 * 组件：食物列表页面视图控件状态
 */
export interface FoodListViewState extends ReactViewState {
    btnState?: any;
    food_list?: any;
    modal?: any;
    list?: any;
    menu_list?: any;
    tabs?: any;
    buy_list?: any;
    price?: any;
    tab_show_list?: any;
    food_data?: any;
}
/**
 * 组件：食物列表页面视图控件
 */
export class FoodListView extends ReactView<FoodListViewControl, FoodListViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            btnState: [],
            menu_list: [
                { 'day': '星期一', 'lunch': '午餐', 'dinner': '晚餐' },
                { 'day': '星期二', 'lunch': '午餐', 'dinner': '晚餐' },
                { 'day': '星期三', 'lunch': '午餐', 'dinner': '晚餐' },
                { 'day': '星期四', 'lunch': '午餐', 'dinner': '晚餐' },
                { 'day': '星期五', 'lunch': '午餐', 'dinner': '晚餐' },
                { 'day': '星期六', 'lunch': '午餐', 'dinner': '晚餐' },
                { 'day': '星期日', 'lunch': '午餐', 'dinner': '晚餐' }
            ],
            food_list: [],
            tabs: [
                { title: '星期一' },
                { title: '星期二' },
                { title: '星期三' },
                { title: '星期四' },
                { title: '星期五' },
                { title: '星期六' },
                { title: '星期日' },
            ],
            buy_list: [],
            modal: false,
            price: 0,
            tab_show_list: [],
            food_data: [],
        };
    }
    // buyBtnChange = (e: any, index: any) => {
    //     console.log(index);
    //     let a = 1 + '-' + index;
    //     console.log("加上序号", 1 + '-' + index);
    //     console.log(a.split('-'));
    //     this.setState({
    //         btnState: 1 + '-' + index
    //     });
    // }
    componentDidMount() {
        let id = this.props.match!.params.key;
        console.log(id);
        // 根据服务商id获取服务产品
        request(this, AppServiceUtility.service_package_service.get_service_product_package_list!({ org_id: id, service_product_type: "助餐服务" }, undefined, undefined))
            .then((data: any) => {
                console.log(data);
                if (data.result.length > 0) {
                    let list = this.state.food_data;
                    data.result.map((item: any) => {
                        list.push({
                            'name': item.catering_week,
                            'data': [{
                                'name': item.catering_time,
                                'data':
                                    [{ 'id': item.id, 'food_name': item.name, 'week': item.catering_week, 'time': item.catering_time, 'food_detail': item.introduce, 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': item.picture_collection, 'price': item.total_price, 'proportion': item.proportion, 'organization_id': item.organization_id, 'is_allowance': item.is_allowance }],
                            },
                            ]
                        });
                    });
                    this.setState({
                        food_data: list
                    });
                    this.listChange('星期一', '午餐');
                }
            });
        this.listChange('星期一', '午餐');
    }
    goPayment = (e: any) => {
        e.nativeEvent.stopImmediatePropagation();
        e.stopPropagation();
        let uuid = getUuid();
        console.log(JSON.stringify(this.state.buy_list));
        const { buy_list } = this.state;
        let divide = {};
        let buy_info: any = [];
        if (this.state.buy_list.length > 0) {
            buy_list.map((item: any) => {
                item['proportion'].map((e: { title: string, contents: number }, i: number) => {
                    switch (e.title) {
                        case "平台":
                            divide['平台'] = {
                                id: divideTitleMap['平台'],
                                percent: e.contents
                            };
                            break;
                        case "服务商":
                            divide["服务商"] = {
                                id: divideTitleMap["服务商"],
                                percent: e.contents
                            };
                            break;
                        case "慈善":
                            divide['慈善'] = {
                                id: divideTitleMap['慈善'],
                                percent: e.contents
                            };
                            break;
                        default:
                            break;
                    }
                });
                buy_info.push({
                    id: item.id,
                    price: item.price,
                    num: item.num,
                    amount_total: item.price * item.num,
                    picture_collection: item.image,
                    subsidy: item.is_allowance === 1 ? item.price : 0,
                    abstract: item.name,
                    pt_id: divide['平台']['id'],
                    pt_percent: divide['平台']['percent'],
                    fw_id: item.organization_id,
                    fw_percent: divide['服务商']['percent'],
                    cs_id: divide['慈善']['id'],
                    cs_percent: divide['慈善']['percent'],
                    // 备注（必要）
                    remarks: '居家服务商品',
                });
            });
            const paramToSend = {
                page_type: PAGE_TYPE.BUY,
                page_info: buy_info,
                // 商户唯一订单号（必要）
                out_trade_no: uuid,
                product_desc: "助餐购买",
                success_url: ROUTE_PATH.paymentSucceed,
                fail_url: ROUTE_PATH.paymentFail,
            };
            const paramToSendStr = JSON.stringify(paramToSend);
            this.props.history!.push(ROUTE_PATH.cleanSubmitOrder + '/' + encodeUrlParam(paramToSendStr));
            // let data = '';
            // this.state.buy_list.forEach((item: any) => {
            //     data !== '' ? data = data + '___' + JSON.stringify(item) : data = JSON.stringify(item);
            //     console.log(data);
            // });
            // this.props.history!.push(ROUTE_PATH.foodSubmitOrder + '/' + data);
        } else {
            Toast.fail('你还未选择商品！！！', 1);
        }
    }
    onClose = () => {
        this.setState({
            modal: false,
        });
    }
    showModal = (e: any) => {
        e.preventDefault(); // 修复 Android 上点击穿透
        this.setState({
            modal: true,
        });
    }
    // 添加购物车
    addFood = (e: any, id: any, name: any, day: any, time: any, price: any, food_detail: any, image: any, is_allowance: any, proportion: any, organization_id: any) => {
        e.stopPropagation();
        Toast.success('加入购物车成功！！', 1);
        console.log(id + ">>>>>>>" + name);
        // 拿到食物的id
        let buy_list = this.state.buy_list;
        buy_list.push({ 'id': id, 'name': name, 'num': 1, 'day': day, 'time': time, 'price': price, 'food_detail': food_detail, 'image': image, 'is_allowance': is_allowance, 'proportion': proportion, 'organization_id': organization_id });
        let list = this.state.btnState;
        list.map((item: any) => {
            if (item.id === id) {
                item.state = true;
            }
        });
        console.log(list);
        console.log(buy_list);
        let allPrice = this.state.price + price;
        this.setState({
            buy_list,
            btnState: list,
            price: allPrice
        });
        this.listChange(day, time);
        this.btnDisable(id);
        this.tab_click({ 'title': '星期一' }, 0);
    }
    // 查找按钮的状态
    btnDisable = (id: any) => {
        if (this.state.btnState.length > 0) {
            let btnState = false;
            this.state.btnState.map((item: any) => {
                if (item.id === id) {
                    return btnState = item.state;
                }
            });
            console.log(btnState);
            return btnState;
        }
        return false;
    }
    // 购物详情数量变化回调
    stepChange = (value: any, id: any, day: any, time: any, price: any, tabIndex: any) => {
        console.log(value);
        let list = this.state.buy_list;
        let btnState = this.state.btnState;
        let allPrice = 0;
        console.log("list>>>>>>>>>", list);
        list.map((item: any, index: any) => {
            if (value === 0) {
                if (item.id === id) {
                    allPrice = this.state.price - price;
                    list.splice(index, 1);
                    btnState.map((items: any) => {
                        if (items.id === id) {
                            items.state = false;
                        }
                    });
                    this.listChange(day, time);
                    this.tab_click({ 'title': day }, tabIndex);
                }
            } else {
                if (item.id === id) {
                    console.log(value);
                    // allPrice = value * price;
                    if (value >= item.num) {
                        allPrice = this.state.price + price;
                    } else {
                        allPrice = this.state.price - price;
                    }
                    item.num = value;
                    this.listChange(day, time);
                    this.tab_click({ 'title': day }, tabIndex);
                }
            }
        });

        this.setState({
            buy_list: list,
            btnState,
            price: allPrice
        });
    }
    // 根据星期几以及早餐还是午餐查询对应的服务产品
    listChange = (day: any, time: any) => {
        // console.log(1);
        let food_list: any = [];
        // 传过来星期和早餐/午餐发送请求
        this.state.food_data.map((items: any, indexs: any) => {
            // console.log(2);
            // console.log(items);
            if (items.name === day) {
                items.data.map((i: any, idx: any) => {
                    // console.log(3);
                    if (i.name === time) {
                        i.data.map((item: any, index: any) => {
                            // console.log(4);
                            let list = this.state.btnState;
                            if (list.length > 0) {
                                let idList: any = [];
                                list.map((listItem: any) => {
                                    idList.push(listItem.id);
                                });
                                if (!idList.includes(item.id)) {
                                    list.push({ 'id': item.id, 'state': false });
                                    this.setState({
                                        btnState: list
                                    });
                                } else {
                                    this.setState({
                                        btnState: list
                                    });
                                }
                            } else {
                                list.push({ 'id': item.id, 'state': false });
                                this.setState({
                                    btnState: list
                                });
                            }
                            console.log(this.state.btnState);
                            let food = (
                                <div className="food-list" key={index} onClick={() => this.goDetails(item.id)} style={{ margin: '0px' }}>
                                    <Card className='list-conten'>
                                        <Row type='flex' justify='center'>
                                            <Col className='list-col' span={12} style={{ padding: '0px' }}><img src={item.image} style={{ height: '72pt', width: '130px' }} /></Col>
                                            <Col span={12} className='list-col'>
                                                <Row><strong>{item.food_name}</strong></Row>
                                                <Row>
                                                    {/* <Col span={10}>
                                                        {item.food_detail.map((item: any, index: any) => {
                                                            return <p style={{ marginBottom: '0px' }} key={index}>{item.option_content}</p>;
                                                        })}
                                                    </Col> */}
                                                    {/* <span></span> */}
                                                    <Button disabled={this.btnDisable(item.id)} type="warning" size="small" style={{ float: "right" }} onClick={(e: any) => { this.addFood(e, item.id, item.food_name, day, time, item.price, item.food_detail, item.image, item.is_allowance, item.proportion, item.organization_id); }}>购买</Button>
                                                </Row>
                                                <Row>￥{item.price}</Row>
                                                <Row>
                                                    <Col span={12}>{item.week}</Col>
                                                    <Col span={12}>{item.time}</Col>
                                                </Row>
                                            </Col>
                                        </Row>
                                    </Card>
                                </div>
                            );
                            food_list.push(food);
                            this.setState({
                                food_list
                            });
                        });
                    } else {
                        food_list = [];
                        let food = (<div className="food-list" key={idx} style={{ textAlign: 'center' }}>暂无更多产品...</div>);
                        food_list.push(food);
                        this.setState({
                            food_list
                        });
                    }
                });
            } else {
                food_list = [];
                let food = (<div className="food-list" key={indexs} style={{ textAlign: 'center' }}>暂无更多产品...</div>);
                food_list.push(food);
                this.setState({
                    food_list
                });
            }
        });
    }
    // 购物车状态栏切换
    tab_click = (tab: any, index: any) => {
        console.log("切换>>>>>>>>>", tab, index);
        let tab_show_list: any = [];
        this.state.buy_list.map((item: any) => {
            if (item.day === tab.title) {
                item = { ...item, 'index': index };
                tab_show_list.push(item);
            }
        });
        this.setState({
            tab_show_list
        });
        console.log("数据据", this.state.tab_show_list);
    }

    // 跳转到详情页
    goDetails = (id: any) => {
        // e.nativeEvent.stopImmediatePropagation();
        // e.stopPropagation();
        this.props.history!.push(ROUTE_PATH.foodDetails + '/' + id);
    }
    render() {
        return (
            <div style={{ paddingLeft: '6px', paddingRight: '6px' }}>
                <div className="food-list-content">
                    {/* <Menu
                    className="single-foo-menu"
                    data={this.state.data}
                    value={['1']}
                    level={1}
                    onChange={this.onChange}
                    height={document.documentElement.clientHeight}
                /> */}
                    <Accordion className="single-foo-menu" style={{ marginRight: '6px' }}>
                        {this.state.menu_list.map((item: any, index: any) => {
                            return (
                                <Accordion.Panel header={item.day} key={index}>
                                    <List className="my-list">
                                        <List.Item onClick={() => { this.listChange(item.day, item.lunch); }}>{item.lunch}</List.Item>
                                        <List.Item onClick={() => { this.listChange(item.day, item.dinner); }}>{item.dinner}</List.Item>
                                    </List>
                                </Accordion.Panel>
                            );
                        })}
                    </Accordion>
                    {this.state.food_list.length > 0 ? this.state.food_list.map((item: any) => {
                        return item;
                    })
                    :
                    <div className='food-list' style={{textAlign:'center'}}>该服务商暂时没有服务产品</div>
                    }
                </div>
                <div style={{ overflow: 'hidden', backgroundColor: '#1890ff', width: '90%', height: '35px', position: 'fixed', bottom: '0px', left: '0px', borderRadius: '15px', marginLeft: '15px', marginRight: '15px' }}>
                    <div style={{ float: 'left', width: '50%', textAlign: 'center', lineHeight: '35px' }} onClick={this.showModal}>选购详情</div>
                    <div style={{ float: 'right', width: '30%', textAlign: 'center', lineHeight: '35px', borderLeft: "1px solid rgb(14, 12, 12)" }} onClick={this.goPayment}>确认订单</div>
                </div>
                <Modal
                    popup={true}
                    visible={this.state.modal}
                    onClose={this.onClose}
                    animationType="slide-up"
                    style={{ overflow: 'scroll', height: '300px' }}
                    className='food-list-modal'
                >
                    <Tabs
                        tabs={this.state.tabs}
                        initialPage={0}
                        onTabClick={(tab, index) => this.tab_click(tab, index)}
                    >
                        <List renderHeader={() => <div>选购详情</div>} style={{ overflow: 'scroll' }}>
                            {this.state.tab_show_list.map((item: any) => (
                                <List.Item key={item.id} style={{ overflow: 'scroll' }}>{item.name}<Stepper key={item.id} value={item.num} showNumber={true} max={10} min={0} onChange={(value) => { this.stepChange(value, item.id, item.day, item.time, item.price, item.index); }} /></List.Item>
                            ))}
                        </List>
                    </Tabs>
                    <List.Item>
                        <Button type="primary" onClick={this.onClose} style={{ position: 'fixed', bottom: '0px', width: '100%', left: '0px' }}>￥{this.state.price}</Button>
                    </List.Item>
                </Modal>
            </div>
        );
    }
}

/**
 * 组件：食物列表页面视图控件
 * 控制食物列表页面视图控件
 */
@addon('FoodListView', '食物列表页面视图控件', '控制食物列表页面视图控件')
@reactControl(FoodListView, true)
export class FoodListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}